package net.lengwang.iot.middleware.packet.response;

import java.nio.ByteBuffer;
import java.time.LocalDateTime;

import net.lengwang.iot.middleware.packet.ParsedPacket;

public abstract class ResponsePacket {
    protected final static byte START_FLAG = (byte) 0xEB;
    protected final static byte END_FLAG = (byte) 0xBE;
    protected byte PACKET_LENGTH = (byte) 0x04;
    protected byte COMMAND = (byte) 0x90;
    public final static byte[] CRC16 = { 0x00, 0x00 };

    protected ParsedPacket parsedPacket;
    protected ParsedPacket responsePacket;

    public ResponsePacket(ParsedPacket parsedPacket) {
        this.parsedPacket = parsedPacket;
    }

    public byte[] toByteArray() {
        // 计算所需的缓冲区大小
        int bufferSize = 7; // START_FLAG (2) + PACKET_LENGTH (1) + CRC16 (2) + END_FLAG (2)
        ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
        buffer.put(START_FLAG).put(START_FLAG)
                .put(PACKET_LENGTH);

        buffer.putShort((short) 0x0000) // CRC16
                .put(END_FLAG).put(END_FLAG);

        return buffer.array();
    }

    // 时间传入
    public void setServerTime(byte[] packet, int offset, byte[] serverTime) {
        System.arraycopy(serverTime, 0, packet, offset, serverTime.length);
    }

    // 创建服务器时间
    public byte[] createServerTime() {
        LocalDateTime now = LocalDateTime.now();
        byte[] serverTime = new byte[6];

        serverTime[0] = (byte) (now.getYear() % 100);
        serverTime[1] = (byte) now.getMonthValue();
        serverTime[2] = (byte) now.getDayOfMonth();
        serverTime[3] = (byte) now.getHour();
        serverTime[4] = (byte) now.getMinute();
        serverTime[5] = (byte) now.getSecond();

        // 将每个字节转换为BCD码
        for (int i = 0; i < serverTime.length; i++) {
            serverTime[i] = (byte) ((serverTime[i] / 10 * 16) + (serverTime[i] % 10));
        }

        return serverTime;
    }
}
